package me.seu.demo.service.python;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.python.core.PyByteArray;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

import java.util.List;

/**
 * python解析器
 *
 * @author liangfeihu
 * @since 2022/4/7 10:57
 */
public class PythonResolver {

    private static PythonInterpreter interpreter = new PythonInterpreter();

    public static List<String> generateCode() throws Exception {
        interpreter.exec(scriptText);
        PyFunction pyFunction = interpreter.get("generate_device_no", PyFunction.class);
        PyObject pyObj = pyFunction.__call__(new PyInteger(5));
        System.out.println(pyObj.toString());
        return JSONArray.parseArray(pyObj.toString(), String.class);

    }

    public static void main(String[] args) throws Exception{
        //String generateCode = generateCode();
//        System.out.println(generateCode);
//        Long deviceNo = Long.valueOf(generateCode);
//        System.out.println(deviceNo + 1);
//        System.out.println(deviceNo + 2);
//
//        System.out.println(scriptText);

        List<String> list = generateCode();
        System.out.println(JSONObject.toJSONString(list));
    }

    private static String scriptText = "" +
            "import datetime\n" +
            "import random\n" +
            "\n" +
            "# 此方法用于生成指定数量的随机数字字符串\n" +
            "def generate_code(num):\n" +
            "\tres = \"\"\n" +
            "\tfor _ in range(num):\n" +
            "\t\tres += str(random.randint(0, 9))\n" +
            "\treturn res\n" +
            "\n" +
            "# 此方法用于生成4位生产年月字符串\n" +
            "def generate_time():\n" +
            "\treturn datetime.datetime.now().strftime('%y%m')\n" +
            "\t\n" +
            "def number_str(num):\n" +
            "\tindex = str(num)\n" +
            "\tlength = 4 - len(index)\n" +
            "\tfor i in range(length):\n" +
            "\t\tindex = '0' + index\n" +
            "\treturn index\n" +
            "\n" +
            "# 此方法名切勿修改，用于返回生成的设备编号\n" +
            "# 本示例生成的设备编号格式为：2位产品前缀+4位生产年月+4位随机数+4位流水号，如10220412340001\n" +
            "def generate_device_no(num):\n" +
            "\trandom_list = []\n" +
            "\tindex = 0\n" +
            "\tfor i in range(num):\n" +
            "\t\tindex += 1\n" +
            "\t\tdeviceNo = '10' + generate_time() + generate_code(4) + number_str(index)\n" +
            "\t\trandom_list.append(deviceNo)\n" +
            "\treturn random_list\n";
}
